import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getRoleList, createRole, updateRole, deleteRole, getRoleById, getRoleCategories } from '@/api/role'
import { ElMessage } from 'element-plus'

export const useRoleStore = defineStore('role', () => {
  const roleList = ref([])
  const total = ref(0)
  const loading = ref(false)
  const categories = ref([])

  // 获取角色列表
  const fetchRoleList = async (params = {}) => {
    loading.value = true
    try {
      const data = await getRoleList(params)
      roleList.value = data.records || []
      total.value = data.total || 0
      return data
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取角色分类
  const fetchCategories = async () => {
    try {
      const list = await getRoleCategories()
      categories.value = Array.isArray(list) ? list : []
      return categories.value
    } catch (error) {
      throw error
    }
  }

  // 创建角色
  const createNewRole = async (roleData) => {
    try {
      const data = await createRole(roleData)
      ElMessage.success('角色创建成功')
      return data
    } catch (error) {
      throw error
    }
  }

  // 更新角色
  const updateRoleInfo = async (roleData) => {
    try {
      const data = await updateRole(roleData)
      ElMessage.success('角色更新成功')
      return data
    } catch (error) {
      throw error
    }
  }

  // 删除角色
  const removeRole = async (roleId) => {
    try {
      const data = await deleteRole(roleId)
      ElMessage.success('角色删除成功')
      return data
    } catch (error) {
      throw error
    }
  }

  // 获取角色详情
  const fetchRoleDetail = async (roleId) => {
    try {
      const data = await getRoleById(roleId)
      return data
    } catch (error) {
      throw error
    }
  }

  return {
    roleList,
    total,
    loading,
    categories,
    fetchRoleList,
    fetchCategories,
    createNewRole,
    updateRoleInfo,
    removeRole,
    fetchRoleDetail
  }
})
